#include <CInterface.h>

CGalaxy* CInterface::PointWithinGalaxy(CVector& pos) {

  double radius = 1.0;

  for (int i=0;i<rasterizer.galaxies.size();i++) {
    CGalaxy* g = rasterizer.galaxies[i];
    double dist = (g->params.position - pos).Length();
    
    if (dist<radius) {
      //  cout << "1";
      return g;
    }
  }
  //  cout << "0";
  return NULL;
}


double CInterface::GetSurfaceIntensity(CVector pos, CVector direction) {
  CGalaxy* g = PointWithinGalaxy(pos);
  if (!g)
    return 0;

  return GetGalaxyIntensity(g, pos, direction);
}

double CInterface::GetGalaxyIntensity(CGalaxy* g, CVector& pos, CVector& direction) {
  
  // First, find the ISPs
  CVector isp1, isp2;
  
  double I = 0;
  
  CVector camera = pos;
  
  
  bool is = CVector::intersectSphere(camera - g->params.position, direction, g->params.axis, isp1, isp2);
  float dist = (isp1-isp2).Length();
  
  
  if ((camera-isp1).Length()>(camera-isp2).Length()) {
    CVector tmp = isp1;
    isp1 = isp2;
    isp2 = tmp;
  }
  
  CVector ispDisk;
  CVector::rayIntersectPlane(g->params.position, g->params.orientation, camera, direction, ispDisk);
  
  // it sure as hell should intersect
  
  if (is) {
    rasterizer.getIntensity(g, I, isp1, isp2);
  }
  return I;
	
}


void CInterface::Initialize(int seed, double wavelength) {
  

    try {
      //rasterizer.RP.loadFromIni(inifile);
      
      rasterizer.RP.seed = seed;
      rasterizer.RP.randomize_spectra = 0;
      srand(rasterizer.RP.seed);
      
      
      rasterizer.loadSpectra();
      // Size?
      rasterizer.RP.size = 64;
      rasterizer.RP.wavelength = wavelength;
      
      
      rasterizer.RP.no_procs = 1;
      rasterizer.RP.rank = 0;
      rasterizer.RP.perlin = new Perlin(6,1.0,1.0,rasterizer.RP.seed);
      srand(rasterizer.RP.seed);

      rasterizer.RP.rayStep = 0.05;


  } catch (string s) {
    cout << s<< endl;
    exit(1);
  }


}

CGalaxy* CInterface::AddGalaxy(string file, CVector position, CVector orientation, double magnitude) {
  CGalaxy* g = rasterizer.AddGalaxy(file, position, orientation, magnitude); 
  g->setupComponentWavelength(rasterizer.RP.wavelength);
  return g;
}



